<MudStack>
    <MudToolBar DisableGutters="true">
        <MudText Typo="Typo.h4">@Title</MudText>
        <MudSpacer />
        <MudPaper Outlined="true" Class="flex-grow-1 pb-2 pl-3">
            <MudTextField @bind-Value="_filter" Placeholder="Search products" Adornment="Adornment.Start"
                AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-n2" DisableUnderLine="true">
            </MudTextField>
        </MudPaper>
    </MudToolBar>
    <MudTable Items=@Products Hover="true" Breakpoint="Breakpoint.Sm" AllowUnsorted=true
        Context="product" Dense=true FixedHeader=true RowsPerPage=10 Filter=OnFilter SortLabel="Sort By" Outlined="true">
        <HeaderContent>
            <MudTh>Products</MudTh>
            <MudTh>
                <MudTableSortLabel SortBy=@(new Func<ProductDetails, object>(p => p.Name))>
                    Name
                </MudTableSortLabel>
            </MudTh>
            <MudTh>
                <MudTableSortLabel SortBy=@(new Func<ProductDetails, object>(p => p.Description))>
                    Description
                </MudTableSortLabel>
            </MudTh>
            <MudTh>
                <MudTableSortLabel SortBy=@(new Func<ProductDetails, object>(p => p.Quantity))>
                    Quantity
                </MudTableSortLabel>
            </MudTh>
            <MudTh>
                <MudTableSortLabel SortBy=@(new Func<ProductDetails, object>(p => p.UnitPrice))>
                    Price
                </MudTableSortLabel>
            </MudTh>
        </HeaderContent>
        <RowTemplate>
            <MudTd>
                <MudFab Disabled=@(IsInCart?.Invoke(product) ?? false) Size=Size.Small
                    Color=Color.Primary Icon=@Icons.Material.Filled.AddShoppingCart
                    OnClick=@(async _ => await AddToCartAsync(product.Id))/>
            </MudTd>
            <MudTd DataLabel="Name">@product.Name</MudTd>
            <MudTd DataLabel="Description">@product.Description</MudTd>
            <MudTd DataLabel="Quantity">@product.Quantity.ToString("N0")</MudTd>
            <MudTd DataLabel="Price">@product.UnitPrice.ToString("C2")</MudTd>
        </RowTemplate>
        <PagerContent>
            <MudTablePager />
        </PagerContent>
    </MudTable>
</MudStack>

@code {
    string? _filter;

    [Parameter, EditorRequired]
    public HashSet<ProductDetails> Products { get; set; } = null!;

    [Parameter, EditorRequired]
    public string Title { get; set; } = null!;
    
    [Parameter, EditorRequired]
    public EventCallback<string> OnAddedToCart { get; set; }

    [Parameter, EditorRequired]
    public Func<ProductDetails, bool> IsInCart { get; set; } = null!;

    Task AddToCartAsync(string productId) =>
        OnAddedToCart.HasDelegate
            ? OnAddedToCart.InvokeAsync(productId)
            : Task.CompletedTask;

    bool OnFilter(ProductDetails product) => product.MatchesFilter(_filter);
}